<?php
namespace Api\Model\Amazon;

class ReportDaySaleModel extends CommonModel{
    // 数据表前缀
    protected $tablePrefix   = 'fba_';
    // 数据库配置
    protected $connection    = 'fbawarehouse';
    // 数据表名（不包含表前缀）
    protected $tableName     = 'report_daysale';

    protected $trueTableName = 'fba_report_daysale';

    public function insertData($reportSaleLists){
        $sqlInsert = 'INSERT INTO `fba_report_daysale`(`account_id`, `sku`, `sale`, `sale_date`) VALUES ';

        foreach ($reportSaleLists as $reportSaleList) {

            $insertSqlStr = $sqlInsert . '(\'' . join('\', \'', $reportSaleList) . '\')' .
                ' ON DUPLICATE KEY UPDATE `sale` = `sale` + ' . $reportSaleList['sale'];

            $this->query($insertSqlStr);
        }
        unset($reportSaleLists);
    }

    /**
     * 计算日均销量
     */
    public function daySaleCalculate ($account_id) {
        $brotherAccountIds = D('Amazon\AccountSite')->getBrotherAccountIds($account_id);
        $brotherAccountIdsStr = implode(',',$brotherAccountIds);
        $end_date = date('Y-m-d', strtotime('-1 day'));
        foreach (array(7, 14, 28) as $dayShuttle) {
            $start_date = date('Y-m-d', strtotime('-' . ($dayShuttle + 1) . ' day'));
            $sql = 'SELECT `account_id`,`sku`,SUM(`sale`)/' . $dayShuttle . ' AS `' . $dayShuttle . 'daysale`
            FROM `fba_report_daysale`
            WHERE `sale_date` >= \'' . $start_date . '\'
            AND `sale_date` <= \'' . $end_date . '\'
            AND `account_id` IN ( ' . $brotherAccountIdsStr . ')
            GROUP BY `account_id`, `sku`';

            $aveSaleLists = $this->query($sql);
            if(!empty($aveSaleLists)){
                D('Api/Amazon/ReportStockSale')->insertSaleData($aveSaleLists,$dayShuttle);
            }

        }
    }


}